const { formatTime } = require("../../utils/util");

// pages/interact/interact.js
const app=getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
      showModal:false,
      currentIndex:0,
      videolikeImg:false,
      collectImg:false,
      userId:wx.getStorageSync('user').userId
    },

    computeScrollViewHeight() {
      let query = wx.createSelectorQuery().in(this)
      query.select('.video').boundingClientRect()
      query.exec((res) => {
        let videoHeight = res[0].height;
        let screenHeight = wx.getSystemInfoSync().windowHeight
          let scrollHeight = screenHeight - videoHeight
          this.setData({
            scrollListHeight: scrollHeight
          })
      })
    },


      //查看用户是否对该视频进行点赞
      lookVideoLike:async function(){
        let ret=await new Promise((resolve,reject)=>{
          wx.request({
            url:`${app.globalData.url}/thumb/thumbs_Up?userId=${this.user.userId}&from_Id=${this.videoId}&type=1`,
            success:res=>{
              if(res.statusCode==200){
                this.setData({videolikeImg:true})
                resolve(res.statusCode)
              }else{
                resolve(res.statusCode)
              }
            }
          })
        })
      },

      //将用户点赞的评论改变颜色
      likeArr:[],
      changeComLikecolor:async function(){
        let ret=await new Promise((resolve,reject)=>{
          wx.request({
            url:`${app.globalData.url}/thumb/thumbs_Up?userId=${this.user.userId}&type=2`,
            success:res=>{
              if(res.statusCode==200){
                resolve(res)
              }else{
                resolve(res.statusCode)
              }
            }
          })
        })
    
        let likeCom=ret.data;
        if(likeCom){
          this.likeArr=likeCom.map((comment)=>{
            return comment.from_Id;
          })
        }
      },

      //查看该视频对应的评论
      lookComment:async function(){
        let ret=await new Promise((resolve,reject)=>{
          wx.request({
            url:`${app.globalData.url}/comment/interactive_Comments/${this.videoId}`,  
            success:res=>{
              if(res.statusCode==200){
                resolve(res)
              }
            }
          })
        })
        let comments=ret.data;
        for(var i=0;i<comments.length;i++){
          comments[i].public_Time=formatTime(new Date(comments[i].public_Time))
          if((this.likeArr.indexOf(comments[i].commentId))>=0){
            comments[i].isLike=true
          }else{
            comments[i].isLike=false
          }
        }
        this.setData({comments:comments})
      },

      //查看用户是否对该视频进行收藏
      lookVideoCollect:async function(){
        let ret=await new Promise((resolve,reject)=>{
          wx.request({
          url:`${app.globalData.url}/collect/collections?videoId=${this.videoId}&userId=${this.user.userId}`,
          success:res=>{
            if(res.statusCode==200){
              console.log(res)
              this.setData({collectImg:true})
              resolve(res)
            }else{
              resolve(res.statusCode)
            }
          }
        })})
      },

    playTime:null,
    getcurrentPlaytime:function(e){
      this.playTime=e.detail.currentTime;
    },
    /**
     * 生命周期函数--监听页面加载
     */
    videoId:0,
    videoCtx:null,
    user:null,
    onLoad: function (options) {
      this.user=wx.getStorageSync('user'),
      this.videoId=options.videoId;
      wx.setStorageSync('videoId', this.videoId)
      this.videoCtx=wx.createVideoContext('myVideo')
      //获取用户点击的视频的资源
      wx.request({
        url:`${app.globalData.url}/video/interactive_Video?videoId=${this.videoId}`,
        success:res=>{
          if(res.statusCode==200){
            this.setData({videoObj:res.data[0]})
            this.lookVideoLike();
            this.changeComLikecolor();
            this.lookComment();
            this.lookVideoCollect();
          }else{
            console.log("视频跑丢啦...")
          }
        }
      })

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
      this.computeScrollViewHeight()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
      console.log(this.user)
      clearInterval(this.cacheId);
      wx.request({
        url:`${app.globalData.url}/video/play_history`,
        method:'PUT',
        header:{'content-type':'application/json'},
        dataType:'text',
        data:{
          userId:this.user.userId,
          videoId:this.videoId,
          play_Time:this.playTime
        },
        success:res=>{
          if(res.statusCode==200){
            console.log('save playtime success')
          }
        }
      })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    
    //取消用户对该视频的点赞
    deleteLikeVideo:function(){
      wx.request({
        url:`${app.globalData.url}/thumb/thumbs_Up?from_Id=${this.videoId}&userId=${this.user.userId}&type=1`,
        method:'DELETE',
        dataType:'text',
        success:res=>{
          if(res.statusCode==200){
            this.setData({videolikeImg:false});
          }
        }
      })
    },

    //添加用户对该视频的点赞
    addLikeVideo:function(){
      console.log(this.user);
      wx.request({
        url:`${app.globalData.url}/thumb/thumbs_Up`,
        method:'POST',
        data:{
          from_Id:this.videoId,
          userId:this.user.userId,
          type:1
        },
        header:{'content-type':'application/json'},
        dataType:'text',
        success:res=>{
          if(res.statusCode==200){
            this.setData({videolikeImg:true});
          }
        }
      })
    },

    //用户对视频进行点赞
    likeVideo:function(){
      if(this.data.videolikeImg){
        //如果用户已经点击过喜欢图标则将其删除
        this.deleteLikeVideo()
      }else{
        this.addLikeVideo()
      }
    },

    //点击某条评论的喜欢图标
    bindLikeComment:async function(e){
      let commentId=e.target.id;
      let comments=this.data.comments;
      let that=this;
      for(var i=0;i<comments.length;i++){
        if(comments[i].commentId==commentId){
          if(comments[i].isLike){
            console.log(comments[i].isLike)
            let ret=await new Promise((resolve,reject)=>wx.request({
              url:`${app.globalData.url}/thumb/thumbs_Up?userId=${this.user.userId}&from_Id=${commentId}&type=2`,
              method:'DELETE',
              dataType:'text',
              success:res=>{
                if(res.statusCode==200){
                  resolve(res);
                }
              }
            }))
            comments[i].isLike=false;
            comments[i].thumbsUpNum=comments[i].thumbsUpNum-1;  
            that.setData({comments:comments})
          }else{
            let ret=await new Promise((resolve,reject)=>wx.request({
              url:`${app.globalData.url}/thumb/thumbs_Up`,
              method:'POST',
              dataType:'text',
              header:{'cotent-type':'application/json'},
              data:{
                userId:this.user.userId,
                from_Id:commentId,
                type:2
              },
              success:res=>{
                if(res.statusCode==200){
                  resolve(res);
                }
              }
            }))
            comments[i].isLike=true;
            comments[i].thumbsUpNum=comments[i].thumbsUpNum+1;   
            that.setData({comments:comments})
          }
        }
      }
    },

    //点击评论按钮，出现评论的弹框
    cacheId:0,
    commentVideo:async function(){
      this.setData({
        showModal:true
      })
    },

    cacheTimer:null,
    cacheVal:null,
    cacheContent:function(d){
      this.cacheVal=d.detail.value;
      if(this.cacheTimer) return;
      this.cacheTimer=setInterval(()=>{
        this.cacheTimer=null;
        wx.setStorageSync('cache-content', this.cacheVal)
      },1000)
    },

    //发送评论
    postComment:function(){
      var that=this;
      wx.request({
        url:`${app.globalData.url}/comment/interactive_Comments`,  
        method:'POST',
        data:{
          videoId:this.videoId,
          userId:this.user.userId,
          content:this.cacheVal,
          type:2
        },
        header:{'content-type':'application/json'},
        success:ret=>{
          that.setData({
            showModal:false,
          })
          that.lookComment()
        }
      })
    },

    //取消评论
    cancelComment:function(){
      this.setData({showModal:false})
    },

    //用户删除自己的评论
    deleteComment:function(e){
      wx.request({
        url:`${app.globalData.url}/comment/interactive_Comments/${e.target.id}`,
        method:'DELETE',
        dataType:'text',
        success:res=>{
          if(res.statusCode==200){
            let comments=this.data.comments.filter(item=>{
              return item.commentId!=e.target.id;
            })
            this.setData({comments:comments})
          }
        }
      })
    },

    //取消用户对该视频的收藏
    deleteCollectVideo:function(){
      wx.request({
        url:`${app.globalData.url}/collect/collections?videoId=${this.videoId}& userId=${this.user.userId}`,
        method:'DELETE',
        dataType:'text',
        success:res=>{
          // console.log('delete success')
          if(res.statusCode==200){
            // console.log('delete success')
            this.setData({collectImg:false});
          }
        }
      })
    },

    //添加用户对该视频的收藏
    addCollectVideo:function(){
      wx.request({
        url:`${app.globalData.url}/collect/collections`,
        method:'POST',
        data:{
          videoId:this.videoId,
          userId:this.user.userId,
        },
        header:{'content-type':'application/json'},
        dataType:'text',
        success:res=>{
          if(res.statusCode==200){
            this.setData({collectImg:true});
          }
        }
      })
    },

    //用户对视频进行收藏
    collectVideo:function(){
      // console.log('likeVideo')
      // this.likeorcollectVideo('thumbs_Up','videolikeImg');
      if(this.data.collectImg){
        //如果用户已经点击过收藏图标则将其删除
        this.deleteCollectVideo()
      }else{
        this.addCollectVideo()
      }
    },
})